import { deepCopy, FormControlProps, FormControlState, MainControl } from '@ibiz-core';
import { SyncSeriesHook } from "qx-util";

/**
 * 表单部件
 * @export
 * @class ControlBase
 */
export class FormControl extends MainControl {
  /**
   * 部件状态
   */
  public declare controlState: FormControlState;

  /**
   * 修改表单的数据对象的某一属性的值。
   * 可通过模块扩展增加一系列相关后续操作。
   * @param name 属性名称
   * @param value 属性值
   */
  public async formDataChange(name: string, value: any){
    this.controlState.data[name] = value;
  }

  /**
   * 使用加载功能模块
   * @param props 传入的props
   */
  public useLoad(props: FormControlProps){
    const { viewSubject, controlName } = this.controlState;
    const loadHooks = {
      beforeLoad: new SyncSeriesHook<[], { error: any, param: any, caller: any, fnName: string }>(),
    };
    /**
     * 加载方法
     * @param [opt={}]
     */
    const load = async (opt: any = {})=>{
      try {
        const loadAction = this.controlState.controlAction.loadAction;
        const { controlService, context, viewParams, showBusyIndicator } = this.controlState;
        const dataRef = toRef(this.controlState, 'data');
        
        if(!loadAction){
          return;
        }
        let _context = deepCopy(context);
        let _viewParams = deepCopy(viewParams);
    
        const response = await controlService.get(loadAction, _context, {viewParams: _viewParams}, showBusyIndicator );
        if (!response.status || response.status !== 200) {
          return
        }
        dataRef.value = response.data;
      } catch (error) {
        // todo 错误异常处理
      }
      
    }

    // 订阅viewSubject,监听load行为
    if(viewSubject){
      let subscription = viewSubject.subscribe((args: any)=>{
        if(args.tag == controlName && args.action == "load"){
          load(args.data)
        }
      })
      // 部件卸载时退订viewSubject
      onUnmounted(()=>{
        subscription.unsubscribe();
      })
    }

    return {
      load: load
    }
  }

  /**
   * 安装部件所有功能模块的方法
   * @param props 传入的Props
   * @param [emit] 事件
   */
  public moduleInstall(props: FormControlProps, emit?: Function) {
    const superParams = super.moduleInstall(props, emit);
    const { load } = this.useLoad(props)

    // 扩展表单数值变化的后续逻辑
    const superFormDataChange = this.formDataChange.bind(this);
    this.formDataChange = async (name: string , value: any) => {
      await superFormDataChange(name, value)
      console.log('表单项更新',this.controlState);
    }

    return {
      ...superParams,
      state: this.controlState,
      load,
      formDataChange: this.formDataChange,
    };
  }
}
